import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:provider/provider.dart";

class LockSound extends StatefulWidget {
  final Map info;
  const LockSound({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _LockSoundState();
}

class _LockSoundState extends State<LockSound> {
  bool _openSound = true;
  int _activeIndex = 1;
  final List _items = [{
    "label": "低",
    "value": 1
  }, {
    "label": "较低", 
    "value": 2
  }, {
    "label": "中",
    "value": 3
  }, {
    "label": "较高",
    "value": 4
  }, {
    "label": "高",
    "value": 5
  }];

  @override
  void initState() {
    super.initState();
    Map lockInfo = Provider.of<CommonState>(context, listen: false).lockInfo ?? {};
    setState(() {
      _openSound = lockInfo["lockSound"] == 1;
      _activeIndex = lockInfo["soundVolume"] ?? 1;
    });
  }

  void _refreshLockInfo() {
    lockApi.getLockInfo(int.parse(widget.info["lockId"])).then((res) {
      if (mounted) {
        Provider.of<CommonState>(context, listen: false).setLockInfo(res["data"] ?? {});
        Map lockInfo = jsonDecode(res["data"]["lockInfo"]) ?? {};
        Provider.of<CommonState>(context, listen: false).setLockInfo(lockInfo);
      }
    });
  }

  void _handleSave() async {
    try {
      EasyLoading.show();
      
      // 先尝试通过接口设置
      try {

          if (_openSound) {
            // 设置音量
            await lockApi.lockSetting(int.parse(widget.info["lockId"]), {
              "lockId": widget.info["lockId"],
              "type": 8,
              "value": _activeIndex,
              "changeType": 2
            });
          } else {
            // 设置声音开关
            await lockApi.lockSetting(int.parse(widget.info["lockId"]), {
              "lockId": widget.info["lockId"],
              "type": 6,
              "value": 2,
              "changeType": 2
            });
          }

        _refreshLockInfo();
        EasyLoading.showSuccess("设置成功");
        return;
      } catch (e) {
        // 接口调用失败,尝试TTLock设置
      }


      // 设置声音开关
      TTLock.setLockSoundWithSoundVolume(
        _getVolumeType(),
        widget.info["lockData"],
        () async {

          _refreshLockInfo();
          EasyLoading.showSuccess("设置成功");
        },
        (errorCode, errorMsg) {
          EasyLoading.showError("设置失败: $errorCode, $errorMsg");
        }
      );
    } catch (e) {
      EasyLoading.showError("保存失败");
    }
  }

  TTSoundVolumeType _getVolumeType() {
    if (_openSound) {
      switch (_activeIndex) {
        case 1:
          return TTSoundVolumeType.firstLevel;
        case 2:
          return TTSoundVolumeType.secondLevel;  
        case 3:
          return TTSoundVolumeType.thirdLevel;
        case 4:
          return TTSoundVolumeType.fouthLevel;
        case 5:
          return TTSoundVolumeType.fifthLevel;
        default:
          return TTSoundVolumeType.fifthLevel;
      }
    }
    return TTSoundVolumeType.off;
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "锁声音",
      child: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          MenuBlock(
            items: [
              MenuBlockItem(
                text: "锁声音",
                showArrow: false,
                suffix: CupertinoSwitch(
                  value: _openSound,
                  activeColor: ThemeVars.colorPrimary,
                  onChanged: (value) => setState(() {
                    _openSound = value;
                  })
                )
              )
            ]
          ),
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 12),
            child: Text("功能开启后，你将可以听到智能锁的提示音。包括电量过低，密码错误登提示。"),
          ),
          if (_openSound) MenuBlock(
            title: const Text("请选择锁音量", style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),),
            items: List.generate(_items.length, (index) {
              return MenuBlockItem(
                text: _items[index]["label"],
                showArrow: false,
                suffix: _activeIndex == _items[index]["value"]
                  ? const Icon(Icons.check_circle, color: ThemeVars.colorPrimary,)
                  : const Icon(Icons.circle_outlined, color: ThemeVars.colorPrimary,),
                onTap: () => setState(() {
                  _activeIndex = _items[index]["value"];
                }),
              );
            })
          ),
          Padding(
            padding: const EdgeInsets.only(top: 40),
            child: Button(
              radius: 5,
              type: ButtonType.primary,
              onPressed: _handleSave,
              child: const Text("保存")
            ),
          )
        ],
      ),
    );
  }
}